package com.springbootblog.controller.fontend.thread.async;

public class TestAsyncOne implements Runnable
{
    // 票总数
    private Integer ticketNum = 5;
    // 线程停止标识
    private boolean stop = true;

    @Override
    public void run()
    {
        // 循环体
        while (this.stop)
        {
            buy();
        }
    }

    public synchronized void buy()
    {
        // 获取线程名称
        String name = Thread.currentThread().getName();
        if(this.ticketNum > 0)
        {
            // 扣票
            System.out.println(name + " get ticket:"+this.ticketNum-- );
            try {
                // 模拟延时
                Thread.sleep(100);
            } catch (
                    InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        else
        {
            System.out.println(name + " ticket is over ! ");
            this.stop = false;
        }
    }

    public static void main(String[] args)
    {
        TestAsyncOne testAsyncOne = new TestAsyncOne();
        Thread t1 = new Thread(testAsyncOne,"t1");
        Thread t2 = new Thread(testAsyncOne,"t2");
        Thread t3 = new Thread(testAsyncOne,"t3");
        Thread t4 = new Thread(testAsyncOne,"t4");
        Thread t5 = new Thread(testAsyncOne,"t5");
        Thread t6 = new Thread(testAsyncOne,"t6");
        Thread t7 = new Thread(testAsyncOne,"t7");
        Thread t8 = new Thread(testAsyncOne,"t8");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        // 五张牌 被八个人买，按照正常逻辑，一定有三个人买不到，但是我们现在的程序可不好说
    }

}
